#!/usr/bin/env python
# encoding: utf-8
# waf script for builduing project
# author: Anton Feldmann 
# Copyright 2013 anton.feldmann@gmail.com

import os

name = 'sfif'

major  = 1
minor  = 0
bugfix = 0

name_version = '%s-%d.%d.%d' % (name, major, minor, bugfix)

application = name
version     = '%d.%d.%d' % (major, minor, bugfix)

top = '.'
out = 'build'

def options(opt):
    opt.load('compiler_c compiler_cxx doxygen')
    try:
# you must include the xcode generator in your waf file if you want to use it
       opt.load('xcode doxygen swig')
    except ImportError:
       pass

    opt.add_option('--debug',
                   action='store_true',
                   default=False,
                   help='compile the project in debug mode')

def configure(conf):
    conf.check_waf_version(mini='1.7.13')

    env=conf.env
    opt=conf.options

    env.CC  = 'clang'
    env.CXX = 'clang++'

    env.LIPO = 'lipo'

    env.FRAMEWORK_COCOA = 'Cocoa'
    env.ARCH_COCOA = ['i386', 'x86_64', 'armv6', 'armv7']

    conf.load('compiler_c gcc compiler_cxx gxx doxygen')	

    for arch, tgt in itertools.product(['i386', 'x86_64', 'armv6', 'armv7'], ['dbg','rel']):
        conf.setenv('ios')
        newEnv = conf.env.derive()
        newEnv.detach()
        conf.setenv('ios_' + arch + '_' + tgt, newEnv)

    #... set any target specific flags
    # These flags set up the sysroot for ios based on simulator or device
        if arch.startswith('arm'):
            addflags = [ '-mios-version-min=' + IOS_MIN_VER, '-isysroot' + IOS_SDK_LOC ]
        else:
            addflags = [ '-mios-version-min=' + IOS_MIN_VER, '-isysroot' + IOS_SDK_LOC ]

        conf.env.CCFLAGS += addflags
        conf.env.CXXFLAGS += addflags
        conf.env.MMFLAGS += addflags   
        conf.env.ARCH = arch

    conf.define('SFIF_VERSION', version)
    
    from waflib import Options
    conf.define('SFIF_DEBUG', int(Options.options.debug))
    conf.write_config_header('include/%s/%s_Config.h' % (name,name))

def init(ctx):
    # any other architectures / platforms
 
    for arch in ['i386', 'x86_64', 'armv6', 'armv7']:
        for tgt in ['dbg', 'rel', 'retail']:
            for inheritingClass in (BuildContext, CleanContext, InstallContext, UninstallContext):
                name = inheritingClass.__name__.replace('Context','').lower()
                class tempClass(inheritingClass):
                    # this is used in the next step to actually call the step
                    cmd = name + '_ios_' + arch + '_' + tgt
                    # This must match your environment name, and sets the output directory
                    variant = 'ios_' + arch + '_' + tgt 
                    # These are for testing in your build script, if you need them
                    architecture = arch
                    target = tgt
                    platform = 'ios'
 
      for tgt in ['dbg', 'rel', 'retail']:
          class tempClass(BuildContext):
              cmd = 'lipo_ios_' + tgt
              fun = 'lipo_ios'
              variant = 'ios'
              target = tgt
              platform = 'ios'

def _lipo_lib(ctx, lib_name):
    ctx(rule='lipo -create ${SRC} -output ${TGT}',
        shell = True,
        target = 'lib%s-%s.a' % (lib_name, ctx.target),
        source = ['build/ios_%s_%s/lib%s.a' % (x, ctx.target, lib_name) for x in IOS_ARCHS]
    )
 
def build_ios(ctx):
    for x in ['i386', 'x86_64', 'armv6', 'armv7']:
        waflib.Options.commands.append('build_ios_' + x + '_rel')
 
    waflib.Options.commands.append('lipo_ios_rel')
 
def lipo_ios(ctx):
    """ This creates universal libraries in ios_target made from the architecture
        builds of each lib. """
    _lipo_lib(ctx, 'A')
    _lipo_lib(ctx, 'B')
    _lipo_lib(ctx, 'C')

def build(bld):
    lib = bld(
        features     = ['c'],
        target       = application,
        cflags       = ['-Wall'],
        source       = bld.path.ant_glob(['**/*.m  **/*.c'],remove=False)),
        includes     = 'include',
        install_path = '${PREFIX}/lib',
        mac_plist     = 'Info.plist',
        mac_resources = 'resources/MainMenu.nib resources/MacApp.icns',
        use           = 'COCOA'
        )
	
    cclib = bld(
          features     = ['cxx'],
          target       = application + '_cc',
          cxxflags     = ['-Wall','-std=c++11','-stdlib=libc++'],
          source       = bld.path.ant_glob(['**/*.mm **/*.cxx'],remove=False)),
          includes     = 'include',
          install_path = '${PREFIX}/lib',
          mac_plist     = 'Info.plist',
          mac_resources = 'resources/MainMenu.nib resources/MacApp.icns',
          use           = 'COCOA'
          )

    from waflib import Options
    if Options.options.debug:
       lib.cflags.extend(['-g','-O0'])       
       cc.cflags.extend(['-g','-O0'])
     else:
       lib.cflags.extend(['-O3'])
       cclib.cflags.extend(['-O3'])
     
     bld.install_files('${PREFIX}/include/%s/' % name, bld.path.ant_glob(['**/*.h'], remove=False))
     bld.install_files('${PREFIX}/include/%s/' % name, bld.path.ant_glob(['**/*.hpp'], remove=False))

   pcf = bld(
        features = 'subst',
        source = '%s.pc.in' % name,
        target = '%s.pc' % name,
        install_path = '${PREFIX}/lib/pkgconfig/'
        )

    pcf.env.table.update(
        {'LIBS':'-l%s -l%s_cc'  % (name,name), 
         'VERSION': version,
         'NAME': name,
         'PREFIX': '%s' % Options.options.prefix,
         'INCLUDEDIR': 'include/%s' % name}
        )


from waflib import TaskGen
@TaskGen.extension('.m')
def m_hook(self, node):
        """Alias .m files to be compiled the same as .c files, clang will do the right thing."""
        return self.create_compiled_task('m', node)



from waflib import TaskGen
@TaskGen.extension('.mm')
def mm_hook(self, node):
        """Alias .mm files to be compiled the same as .c++ files, clang++ will do the right thing."""
        return self.create_compiled_task('mm', node)

class mm(Task.Task):
    "Compile MM files into object files"
    run_str = '${CXX} ${ARCH_ST:ARCH} ${MMFLAGS} ${FRAMEWORKPATH_ST:FRAMEWORKPATH} ${CPPPATH_ST:INCPATHS} ${DEFINES_ST:DEFINES} ${CXX_SRC_F}${SRC} ${CXX_TGT_F}${TGT}'
    vars    = ['CXXDEPS'] # unused variable to depend on, just in case
    ext_in  = ['.h'] # set the build order easily by using ext_out=['.h']
